package com.anysoft.login;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.anysoft.HostConstant;
import com.anysoft.MentorConst;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.OpenSignFingerprintConfirmBean;
import com.anysoft.bean.UserBean;
import com.anysoft.event.GestureEvent;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.PreferencesUtils;
import com.anysoft.utils.login.PBKDF2_Utils;
import com.anysoft.view.ViewLoginNinePointPwd;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.anysoft.R.id.ll_login_pwd_bottom;
import static com.anysoft.R.id.ll_login_pwd_top;
import static com.anysoft.R.id.ll_login_pwd_view;
import static com.anysoft.R.id.tv_set_gesture;

/**
 * Created by wwq on 2017/1/18.
 */

public class SetGestureStep2Activity extends BaseActivity {


    public static int PWD_WIDTH = 0;
    public static int PWD_HEIGHT = 0;
    protected ViewLoginNinePointPwd nv;// 九宫格View
    @BindView(R.id.tv_pass)
    TextView tvPass;
    @BindView(ll_login_pwd_bottom)
    LinearLayout llLoginPwdBottom;
    @BindView(tv_set_gesture)
    TextView tvSetGesture;
    @BindView(ll_login_pwd_top)
    LinearLayout llLoginPwdTop;
    @BindView(ll_login_pwd_view)
    LinearLayout llLoginPwdView;
    @BindView(R.id.ll_pass)
    LinearLayout llPass;

    /**
     * 登录密码
     */
    private String pwd = "";
    private UserBean userBean;

    /**
     * 设置的手势密码
     */
    private String gesture_password = "";

    private boolean setSuccess = false;
    private boolean isChangeGesturePwd = false;

    private boolean isShowSkip;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_set_gesture_step);
        ButterKnife.bind(this);

        tvSetGesture.setText("确认手势密码");

        pwd = getIntent().getStringExtra(MentorConst.GET_PASSWORD);
        userBean = mentorApplication.userBean;

        gesture_password = getIntent().getStringExtra(MentorConst.SET_GESTURE_PASSWORD);
        isShowSkip = getIntent().getBooleanExtra(MentorConst.IS_SHOW_SKIP, true);
        isChangeGesturePwd = getIntent().getBooleanExtra(MentorConst.IS_CHANGE_GESTURE_PWD, false);

        if (isShowSkip) {
            tvPass.setVisibility(View.VISIBLE);
        } else {
            llPass.setVisibility(View.VISIBLE);
        }

        llPass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        measure();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    public void measure() {
        WindowManager wm = (WindowManager) getBaseContext().getSystemService(
                Context.WINDOW_SERVICE);

        int height = wm.getDefaultDisplay().getHeight();
        PWD_WIDTH = wm.getDefaultDisplay().getWidth();
        PWD_HEIGHT = height;

        int w = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);

        llLoginPwdTop.measure(w, h);
        PWD_HEIGHT = PWD_HEIGHT - llLoginPwdTop.getMeasuredHeight();

        llLoginPwdBottom.measure(w, h);
        PWD_HEIGHT = PWD_HEIGHT - llLoginPwdBottom.getMeasuredHeight();

        if (PWD_WIDTH != 0 && PWD_HEIGHT != 0) {
            init();
        }
    }

    protected void init() {
        nv = new ViewLoginNinePointPwd(this, PWD_WIDTH, PWD_HEIGHT);
        llLoginPwdView.addView(nv);

        nv.SetOnPwdSetSucessListener(new ViewLoginNinePointPwd.OnPwdSetSucessListener() {
            @Override
            public void OnPwdSetSucessListener(String password) {
                Logger.t(TAG).d("gesture_password---" + password);
                if (gesture_password.equals(password)) {
                    if (TextUtils.isEmpty(gesture_password)) {
                        showToast("缺少密码参数~");
                        return;
                    }
                    MentorLogger.Log(TAG, "password---" + password + ",pwd---" + pwd +
                            ",sp.getString(MentorConst.LAST_LOGIN_USER_ID,)---" + PreferencesUtils.getString(SetGestureStep2Activity.this, MentorConst
                            .LAST_LOGIN_USER_ID, ""));

                    internetOpen(password);
                } else {
                    showToast("两次设置密码不同，请重试");
                }
            }
        });
    }

    private void internetOpen(String password) {
        showLoading(mActivity);
        Map<String, String> params = new HashMap<>();
        params.put("tradePassword", pwd);
        params.put("fundCustomerNo", mentorApplication.userBean.getFundCustomerNo());
        params.put("loginState", "2");//开启或者修改的内容 	1指纹  2手势
        params.put("fingerprintKey", "");
        final byte[] salt = PBKDF2_Utils.getSalt();
        String randomKey = "";
        for (int i = 0; i < 6; i++) {
            randomKey += String.valueOf((int) (Math.random() * 10));
        }
        final String randomFKey = HttpUtils.getMD5(getUUID() + randomKey);
        params.put("randomKey", randomFKey);
        String pwd_key = PBKDF2_Utils.getRawKey(salt, password);
        String local_key = getLocalSecretKey(mActivity, mentorApplication.userBean.getUserId());
        String final_key = HttpUtils.getMD5(pwd_key + local_key);
        MentorLogger.Log(TAG + "---final_key:", final_key);
        params.put("signKey", final_key);
        params.put("mobileStyle", Build.MANUFACTURER);

        Logger.t("-----BASE_URL-----").d(HttpUtils.createRequestUrl(this, HostConstant.LOGIN, params));
        OkGo.<String>post(HostConstant.OPEN_SIGN_FINGER_PRINT_CONFIRM)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        updateInternetOpen(response.body(), salt, randomFKey);

                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                        hideLoading();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void updateInternetOpen(String json, byte[] salt, String randomFKey) {
        hideLoading();
        OpenSignFingerprintConfirmBean bean;
        try {
            bean = new Gson().fromJson(json, OpenSignFingerprintConfirmBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }

        updateGesture(userBean, salt, randomFKey);

        setSuccess = true;
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (!isChangeGesturePwd) {
            EventBus.getDefault().post(new GestureEvent(setSuccess));
        }
    }

    @OnClick(R.id.tv_pass)
    public void onClick() {
        finish();
    }
}
